<?php
namespace app\api\controller\haipi;

use app\admin\model\UserMoneyLog;
use app\common\controller\Frontend;
use app\common\model\haipi\TicketToken;
use app\common\model\haipi\TicketTokenLog;
use think\facade\Db;

class Recharge extends Frontend{
    public function token(){
        $token = $this->request->post('token');

        if(empty($token)){
            $this->error('缺少参数!');
        }

        $ticketToken = TicketToken::where('token', $token)->find();
        if(empty($ticketToken)){
            $this->error('卡密不正确');
        }
        if($ticketToken->status == 1){
            $this->error("卡密被使用");
        }

        Db::transaction(function()use($ticketToken){
            //修改卡密状态
            $ticketToken->status = 1;
            $ticketToken->save();
            
            //卡密使用日志
            TicketTokenLog::create([
                'user_id' => $this->auth->getUserInfo()['id'],
                'token_id' => $ticketToken->id
            ]);
            
            //余额冲值
            UserMoneyLog::create([
                'memo' => '卡密冲值',
                'money' => $ticketToken->price,
                'user_id' => $this->auth->getUserInfo()['id']
            ]);

        });
        $this->success('冲值成功');
    }
}